import pygame

FACING_LEFT = 0
FACING_RIGHT = 1


ANIMATION_STOP_ON_END = 0
ANIMATION_LOOP = 1


class AnimatedSprite(object):
    def __init__(self, spriteSheet):
        self.spriteSheet = spriteSheet
        self.animationIndex = None
        self.frameDelay = 10
    
    def set_animation(self, animationIndex, frames, isLoop):
        if (self.animationIndex == animationIndex):
            return
        self.animationIndex = animationIndex
        self.frames = frames
        self.frameIndex = 0
        self.frameFraction = 0
        self.isLoop = isLoop
        
    def set_position(self, position, facing=None):
        self.position = position
        if facing != None: self.facing = facing
        elif self.facing == None: self.facing = 0
        
    def draw_frame(self, destination):
        self.spriteSheet.draw(destination, self.position, self.animationIndex, self.frames[self.frameIndex], self.facing)
        
        
        self.frameFraction = (self.frameFraction + 1) % self.frameDelay
        
        if self.frameFraction != 0:
            return
        
        
        nextFrameIndex = self.frameIndex + 1
        
        if nextFrameIndex < len(self.frames):
            self.frameIndex = nextFrameIndex
        elif self.isLoop:
            self.frameIndex = 0
        else:
            pass
        

class SpriteSheet(object):
    def __init__(self, surface, frameWidth, frameHeight):
        mirroredSurface = pygame.transform.flip(surface, True, False)
        
        self.surface = (surface, mirroredSurface)
        
        maxframe = (surface.get_width() / frameWidth) - 1
        
        self.get_rect = (
            lambda animationIndex, frameIndex: (frameIndex*frameWidth, animationIndex*frameHeight, frameWidth, frameHeight)
            ,
            lambda animationIndex, frameIndex: ((maxframe-frameIndex)*frameWidth, animationIndex*frameHeight, frameWidth, frameHeight)
        )
        
        
    def draw(self, destSurface, destPos, animationIndex, frameIndex, facing):
        sourceRect = self.get_rect[facing](animationIndex, frameIndex)
        destSurface.blit(self.surface[facing], destPos, sourceRect)